package com.lan;


import com.lan.antlr.ScriptLexer;
import com.lan.antlr.ScriptParser;
import com.lan.parse.Resolver;
import com.lan.parse.SymbolTree;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

public class ScriptCompiler {

    private ScriptContext context;

    private ScriptLexer lexer;

    private ScriptParser parser;

    public ScriptContext compile(String script) {
        context = new ScriptContext();
        //词法分析
        lexer = new ScriptLexer(CharStreams.fromString(script));
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        //语法分析
        parser = new ScriptParser(tokens);
        context.setAst(parser.prog());
//        语义分析
        ParseTreeWalker walker = new ParseTreeWalker();

        //多步的语义解析。
        //优点：1.代码更清晰；2.允许使用在声明之前，这在支持面向对象、递归函数等特征时是必须的。
        //pass1：类型和Scope
//        TestScriptBaseListener pass1 = new TestScriptBaseListener(context);
//        walker.walk(pass1, context.getAst());

        Resolver pass1 = new Resolver(context);
        walker.walk(pass1, context.getAst());

        SymbolTree symbolTree = context.getSymbolTree();
//        TypeAndScopeScanner scopeScanner = new TypeAndScopeScanner(context);
//        walker.walk(scopeScanner, context.getAst());
//
//        TypeResolver typeResolver = new TypeResolver(context);
//        walker.walk(typeResolver, context.getAst());


        return context;
    }


}
